package com.liyu.rabbit.producer;

import com.liyu.rabbit.consumer.DlxConsumer;
import com.liyu.rabbit.factory.RabbitFactory;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmCallback;

import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @author 李誉
 * @date 2022-06-26 22:17
 * @description 死信队列生产者
 */
public class DlxProducer {

    public static void main(String[] args) throws Exception {
        // 创建信道
        Channel channel = RabbitFactory.createNewChannel();
        // 开启发布确认
        channel.confirmSelect();

        // 添加发布确认监听
        ConfirmCallback ack = (deliveryTag, multiple) -> {
            System.out.println("消息" + deliveryTag + "发布成功。");
        };
        ConfirmCallback nack = (deliveryTag, multiple) -> {
            System.out.println("消息" + deliveryTag + "发布失败。");
        };
        channel.addConfirmListener( ack, nack);

        // 声明直连交换机
        channel.exchangeDeclare(DlxConsumer.NORMAL_HELLO_EXCHANGE, BuiltinExchangeType.DIRECT);

        // 声明队列: 队列名称， 是否持久化， 是否独占， 是否自动删除， 其他参数
//        channel.queueDeclare(DlxConsumer.NORMAL_HELLO_QUEUE, true, false,  false, null);

        // 建立交换机和路由绑定关系
        channel.queueBind(DlxConsumer.NORMAL_HELLO_QUEUE, DlxConsumer.NORMAL_HELLO_EXCHANGE, DlxConsumer.NORMAL_HELLO_QUEUE);

        BasicProperties basicProperties = new BasicProperties("text/plain",
                null,
                null,
                2,
                0, null, null,
                // 到期时间:10s
//                "10000",
                null,
                null, null, null, null,
                null, null);

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入发送的消息");
        String msg = null;
        while (scanner.hasNext()) {
            msg = scanner.next();
            if (msg == null || "".equals(msg)) {
                continue;
            }
//            发一条消息
//            channel.basicPublish(DlxConsumer.NORMAL_HELLO_EXCHANGE, DlxConsumer.NORMAL_HELLO_QUEUE, basicProperties, msg.getBytes(StandardCharsets.UTF_8));
//           一次多发几条消息，超出队列长度
            channel.basicPublish(DlxConsumer.NORMAL_HELLO_EXCHANGE, DlxConsumer.NORMAL_HELLO_QUEUE, basicProperties, (msg+"1").getBytes(StandardCharsets.UTF_8));
            channel.basicPublish(DlxConsumer.NORMAL_HELLO_EXCHANGE, DlxConsumer.NORMAL_HELLO_QUEUE, basicProperties, (msg+"2").getBytes(StandardCharsets.UTF_8));
            channel.basicPublish(DlxConsumer.NORMAL_HELLO_EXCHANGE, DlxConsumer.NORMAL_HELLO_QUEUE, basicProperties, (msg+"3").getBytes(StandardCharsets.UTF_8));

            System.out.println("请输入发送的消息");
        }
    }
}
